package cc.messcat.dao.helpperson;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cc.messcat.common.dao.BaseDaoImpl;
import cc.messcat.common.model.Pager;
import cc.messcat.dao.area.AreaDao;
import cc.messcat.entity.area.Area;
import cc.messcat.entity.fupin.PoorFamily;
import cc.messcat.entity.helpPerson.HelpPerson;
import cc.messcat.entity.helpUnits.HelpUnits;
import cc.messcat.entity.system.McUser;
import cc.messcat.util.Collections;
import cc.messcat.util.LevelUtil;
import cc.messcat.web.system.HelpunitsController;


@Repository
public class HelppersonDaoImpl extends BaseDaoImpl<HelpPerson> implements HelppersonDao {

	@Autowired
	AreaDao areaDao;
	
	@Override
	public List<HelpPerson> getPageNew(String sql) {
		 SQLQuery query = this.getCurrentSession().createSQLQuery(sql);
		
		query.addScalar("id", StandardBasicTypes.LONG).addScalar("duty_id", StandardBasicTypes.LONG).addScalar("date",StandardBasicTypes.DATE)
		.addScalar("name", StandardBasicTypes.STRING).addScalar("sex", StandardBasicTypes.STRING).addScalar("ID_number", StandardBasicTypes.STRING)
		.addScalar("Job_level", StandardBasicTypes.STRING).addScalar("face", StandardBasicTypes.STRING).addScalar("education", StandardBasicTypes.STRING)
		.addScalar("technical", StandardBasicTypes.STRING).addScalar("telephone_number", StandardBasicTypes.STRING).addScalar("Prepared_by", StandardBasicTypes.STRING)
		.addScalar("Prepared_time", StandardBasicTypes.DATE).addScalar("Modifier", StandardBasicTypes.STRING).addScalar("update_time", StandardBasicTypes.DATE)
		.addScalar("Affiliation", StandardBasicTypes.STRING).addScalar("Unit_name", StandardBasicTypes.STRING).addScalar("helpUnitName", StandardBasicTypes.STRING);
		
		query.setResultTransformer(Transformers.aliasToBean(HelpPerson.class));   
		
		return query.list();
	}

	@Override
	public boolean helppesonJudge(Long id) {
		String sql="SELECT * FROM helpperson WHERE id IN(SELECT person_id  FROM help_team_person WHERE person_id = "+id+" AND STATUS = '1')";
		List list = getCurrentSession().createSQLQuery(sql).list();
		if(list != null && !list.isEmpty()){
			return true;
		}
		return false;
	}

	/**
	 * 列出帮扶人关联的村
	 * @param id
	 * @return
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<PoorFamily> listPoorFamily(Long id) {
		List ids = getCurrentSession().createSQLQuery("select poorFamilyId from HELP_PERSON_AND_POOR_FAMILY where helpPersonId="+id).list();

		if(Collections.isEmpty(ids)) {
			return new ArrayList<>(0);
		}
		return getCurrentSession().createQuery(" from PoorFamily where id in( "
			+Arrays.toString(ids.toArray()).replaceAll("[\\[\\]]", "") + ")").list();
	}

	/**
	 * 更新帮扶人贫困户中间表
	 * @param unaffectedPF
	 * @param id
	 */
	@Override
	public void updateHelpPersonAndPoorFamily(ArrayList<PoorFamily> unaffectedPF,Long id) {
	
		ArrayList<Object> ids = new ArrayList<>();
		for(PoorFamily pf : unaffectedPF) {
			ids.add(pf.getId());
		}
		if(Collections.isEmpty(ids)) {
			getCurrentSession().createSQLQuery(" delete from HELP_PERSON_AND_POOR_FAMILY where helpPersonId="+id).executeUpdate();
		} else {
			getCurrentSession().createSQLQuery(" delete from HELP_PERSON_AND_POOR_FAMILY "
				+ "where poorFamilyId not in( " +Arrays.toString(ids.toArray()).replaceAll("[\\[\\]]", "") + ") and helpPersonId=" + id ).executeUpdate();
		}
	}
	
	/**
	 * 更新帮扶人贫困户中间表
	 * @param id
	 */
	@Override
	public void updateHelpPersonAndPoorFamily(Long id) {
		getCurrentSession().createSQLQuery(" delete from HELP_PERSON_AND_POOR_FAMILY where helpPersonId="+id).executeUpdate();
	}

	/**
	 * 根据帮扶单位id获取帮扶人
	 * @param id
	 * @return
	 */
	@Override
	public List<HelpPerson> getByHelpUnit(Long id) {
		return (List<HelpPerson>) getCurrentSession().createQuery("  from HelpPerson where helpUnit="+id).list();
	}

	@Override
	public List<Map<Object,Object>> checkHelpPersonAndPoorFamily(Long id) {
		return getCurrentSession().createSQLQuery("select * from HELP_PERSON_AND_POOR_FAMILY where helpPersonId="+id).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	}

	@Override
	public Pager listHelpPerson(Integer pageNo, Integer pageSize,McUser user, String unitName, String name, String idNumber,
		String tel) {
		StringBuilder fragment = new StringBuilder(" from helpperson where status='1' ");
		if(StringUtils.isNotBlank(unitName)) {
			fragment.append(" and unit_name like '%"+ unitName+"%'");
		}
		if(StringUtils.isNotBlank(name)) {
			fragment.append(" and name like '%"+ name+"%'");
		}
		if(StringUtils.isNotBlank(idNumber)) {
			fragment.append(" and id_number like '%"+ idNumber+"%'");
		}
		if(StringUtils.isNotBlank(tel)) {
			fragment.append(" and telephone_number like '%"+ tel+"%'");
		}
		if(user.getUserLevel().getLevel() >= LevelUtil.TOWN ) {
			Area area = user.getArea();
			fragment.append( " and HELP_UNITNAME = '"+ (area != null ? area.getArea() : "none") +"'");
		}
		String fields = " select id as id,duty_id as duty_id,name as name,sex as sex,ID_number as ID_number,"
			+ " Job_level as Job_level, Unit_name as Unit_name,face as face,technical as technical,telephone_number as telephone_number,"
			+ " Modifier as Modifier,update_time as update_time ";
		List list = getCurrentSession().createSQLQuery(fields + fragment.toString()).setFirstResult((pageNo-1) * pageSize).setMaxResults(pageSize).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
		BigInteger rows = (BigInteger) getCurrentSession().createSQLQuery("select count(*)" + fragment).uniqueResult();
		return new Pager(pageSize,pageNo,rows.intValue(),list);
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> listPoorFamilyByHelpPerson(Long helpPersonID) {
		
		return getCurrentSession()
			.createSQLQuery(" select * from poorfamilylistview as pf,HELP_PERSON_AND_POOR_FAMILY as t1 where pf.id=t1.poorFamilyId and t1.helpPersonId = :helpPersonID")
			.setLong("helpPersonID", helpPersonID).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<HelpUnits> getHelpUnitByHelpPersonID(Long id) {
		return getCurrentSession()
				.createSQLQuery(" select "
						+ " id as id, Affiliation as affiliation , Contact_phone as ContactTel, "
						+ " Contacts as contacts, Mail_box as mail, Modifier as modifier , "
						+ " Postal_Code as postCode, Unit_address as address, Unit_id as unitNumber, Unit_name as unitName, Unit_type as unitType, city as city, country as country, county as county, province as province, work_telephone as tel "
						+ " from helpunits where is_del='1' and id=(select help_unit from helpperson where id = :id )")
				.setLong("id", id).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	}

}
